// pages/login/index.js
import Toast from '@vant/weapp/toast/toast'
import request from '../../utils/request'
const app = getApp()

Page({
  data: {
    id: '',
    password: '',
    idMsg: ' ',
    passwordMsg: ' '
  },
  checkId() {
    let msg
    if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(this.data.id)) {
      msg = '请输入正确的身份证号'
    } else {
      msg = ' '
    }
    this.setData({ idMsg: msg })
  },
  checkPassword() {
    let msg
    if (!/^[a-zA-Z0-9]{4,16}$/.test(this.data.password)) {
      msg = '密码必须由字母或数字组成，长度4-16位'
    } else {
      msg = ' '
    }
    this.setData({ passwordMsg: msg })
  },
  async login() {
    this.checkId()
    this.checkPassword()
    if (this.data.idMsg !== ' ' || this.data.passwordMsg !== ' ') return
    const requestData = { id: this.data.id, password: this.data.password }
    const data = await request.post('/mvs/owner/login', requestData)
    app.globalData.token = data.token
    request.token = data.token
    Toast.success('登录成功')
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/index/index'
      })
    }, 1500)
  }
})
